package top.goldenyear.porpoise.framework.view.core.enjoy;

import cn.hutool.v7.core.text.StrUtil;
import com.jfinal.template.source.ClassPathSource;
import com.jfinal.template.source.FileSource;
import com.jfinal.template.source.ISource;
import com.jfinal.template.source.ISourceFactory;
import java.io.File;
import lombok.extern.slf4j.Slf4j;

/**
 * @author airhead
 */
@Slf4j
public class FileAndClassPathSourceFactory implements ISourceFactory {
  @Override
  public ISource getSource(String baseTemplatePath, String fileName, String encoding) {
    // 先从文件寻找资源，找不到再从类路径寻找资源
    String path =
        StrUtil.isEmpty(baseTemplatePath) ? fileName.substring(1) : baseTemplatePath + fileName;
    boolean exists = new File(path).exists();
    log.info("{}, {}, {}, {}", baseTemplatePath, fileName, path, exists);
    if (exists) {
      return new FileSource(baseTemplatePath, fileName, encoding);
    }

    return new ClassPathSource(baseTemplatePath, fileName, encoding);
  }
}
